package com.primaryedu.ui.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ClearCacheRequest;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.adapter.MainMenuAdapter;
import com.primaryedu.adapter.VideoAdapter;
import com.primaryedu.bean.MicroCourseBean;
import com.primaryedu.bean.NoticeAllBean;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.ui.course.CourseDetailActivity;
import com.primaryedu.utils.Logger;
import com.primaryedu.utils.Utils;
import com.primaryedu.widget.MyListView;
import com.primaryedu.widget.PullToRefreshView;
import com.primaryedu.widget.PullToRefreshView.OnFooterRefreshListener;
import com.primaryedu.widget.PullToRefreshView.OnHeaderRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import okhttp3.Call;

/**
 * 微课
 *
 * @author jun.wang
 * @description
 * @data 2016年12月13日
 */
@SuppressLint("HandlerLeak")
public class CourseFragment extends Fragment implements OnHeaderRefreshListener, OnFooterRefreshListener {

    private View view;
    MyListView courseListView;
    VideoAdapter videoAdapter;
    private List<MicroCourseBean> courseLists = new ArrayList<>();
    private List<MicroCourseBean> tempLists = new ArrayList<>();
    protected RequestQueue requestQueue = null;

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 1001:
                    if (null != tempLists && tempLists.size() != 0) {
                        videoAdapter = new VideoAdapter(getActivity(), Utils.getCourseList(tempLists));
                        courseListView.setAdapter(videoAdapter);
                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };

    private PullToRefreshView pullToRefreshView;
    private int page = 1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_course, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        init();
    }

    private void init() {
        //volley 缓存
       /* requestQueue = Volley.newRequestQueue(getActivity());
        File cacheDir = new File(getActivity().getCacheDir(), "volley");
        DiskBasedCache cache = new DiskBasedCache(cacheDir);
        requestQueue.start();
        requestQueue.add(new ClearCacheRequest(cache, null));*/

        courseListView = (MyListView) view.findViewById(R.id.courseListView);
        ((TextView) view.findViewById(R.id.title)).setText("微课");
        view.findViewById(R.id.back).setVisibility(View.GONE);

        courseListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Intent intent = new Intent(getActivity(), CourseDetailActivity.class);
                intent.putExtra("newId", tempLists.get(position).getId());
                intent.putExtra("type", "1");
                intent.putExtra("videoUrl", tempLists.get(position).getVideourl());
                startActivity(intent);
            }
        });

        pullToRefreshView = (PullToRefreshView) view.findViewById(R.id.main_pull_refresh_view);
        pullToRefreshView.setOnHeaderRefreshListener(this);
        pullToRefreshView.setOnFooterRefreshListener(this);
        pullToRefreshView.setLastUpdated(new Date().toLocaleString());

        requestCourse();
    }

    private void requestCourse() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("pageSize", "10");
        params.put("pageNo", page + "");
        OkHttpUtils.post()//
                .url(Contants.getCourse)
                .params(params)//
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println("getokCourse==" + response);

                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");

                                courseLists = new Gson().fromJson(listStr,
                                        new TypeToken<List<MicroCourseBean>>() {
                                        }.getType());
                                tempLists.addAll(courseLists);
                                handler.sendEmptyMessage(1001);
                                System.out.println("bannerLists==" + courseLists);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
       /* StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.getCourse,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("getCourse==" + response);

                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");

                                courseLists = new Gson().fromJson(listStr,
                                        new TypeToken<List<MicroCourseBean>>() {
                                        }.getType());
                                tempLists.addAll(courseLists);
                                handler.sendEmptyMessage(1001);
                                System.out.println("bannerLists==" + courseLists);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                return map;
            }
        };
        requestQueue.add(stringRequest);*/
    }

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                page++;
                requestCourse();
                pullToRefreshView.onFooterRefreshComplete();
            }

        }, 1500);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {
            @Override
            public void run() {
                requestCourse();
                pullToRefreshView.onHeaderRefreshComplete("更新于:"
                        + Calendar.getInstance().getTime().toLocaleString());
                pullToRefreshView.onHeaderRefreshComplete();
                Toast.makeText(getActivity(), "数据刷新完成!", Toast.LENGTH_SHORT).show();
            }

        }, 1500);
    }


}
